<template>
  <div class="web-page-contation">
    <div class="left-service-list">
      <div class="title-web-service">{{menu_info.name}}服务列表</div>
      <el-select
        class="select-service"
        v-model="search"
        filterable
        remote
        reserve-keyword
        placeholder="请输入关键词"
        :remote-method="remoteMethod"
        :loading="loading"
        @change="selectOptionApps">
        <el-option v-for="item in options" :key="item.id" :label="item.appName" :value="item.appId"></el-option>
      </el-select>
      <div class="service-list-box">
        <ul class="service-list-ul">
           <li class="service-item" :class="app_id===item.appId?'is_acitve_li': ''" 
              v-for="(item,index) in menu_info.apps" 
              :key="index"  @click="selectApps(item.appId)">
            <span>{{item.appName}}</span>
          </li>
        </ul>
      </div>
    </div>
    
    <div class="content-params">
      <div class="title-web-service">条件选择</div>
      <el-form :model="prd_from" ref="prd_from" label-width="100px" label-position="top" class="demo-dynamic">
      <div class="params-box-box no-scoller-box select-service rewiret-scoller">
        <template v-for="(item,key) in prd_from.params">
          <el-form-item :key="key" :label="item.paramShowname"
            :prop="'params.' + key + '.value'"
            :rules="item.required === 1?[{ required: true, message: '请输入', trigger: !item.forSelect?'blur':'change' }]:[]">
            <span slot="label">
              {{item.paramShowname}}
              <el-tooltip v-if="item.paramDescription" class="item" effect="dark" :content="item.paramDescription" placement="top-start">
                <i class="el-icon-question"></i>
              </el-tooltip>
            </span>
            <el-input  v-model="item.value" :placeholder="`请输入${item.paramShowname}`"
              v-if="item.forSelect === '' || item.forSelect === null">
            </el-input>
            <!-- <el-select style="width:100%" v-model="item.value" :placeholder="`请选择${item.paramShowname}`"
              >
              <el-option v-for="(val,keys) in item.forSelect.split(',')" :value="val" :label="val" :key="keys"></el-option>
            </el-select> -->
            <el-autocomplete v-else style="width:100%" v-model="item.value" :placeholder="`请选择或者输入${item.paramShowname}`"
              :fetch-suggestions="querySearch" @focus="selectItem = item">
            </el-autocomplete>
          </el-form-item>
          
        </template>
      </div>
      </el-form>
      <div class="center-button">
        <el-button class="diosyong" :disabled="isVisitor || !apps_info.id" type="primary" @click="sendApi('prd_from')">发起调用</el-button>
      </div>
    </div>
    
    <div class="right-response">
      <div class="title-web-service">API服务实际URL</div>
      <div class="copy-right" @click="copy(url)">
        <i class="top-icon icon-copy"></i>
        <span>复制</span>
      </div>
      <div class="no-scoller-box textarea-top">{{url}}</div>
      <div class="copy-right" @click="copy(is_request_debug ? debug.data : apps_info.base.returnDemo)">
        <i class="top-icon icon-copy"></i>
        <span>复制</span>
      </div>
      <div class="div-box">
        <div class="left">API返回结果</div>
      </div>
      <div class="beizhu">返回结果超过30K，可能会导致浏览器内存溢出，复制失败</div>
      <!-- {{apps_info.base.returnDemo}} -->
      <div class="no-scoller-box textarea-top">{{is_request_debug ? debug.data : apps_info.base.returnDemo}}</div>
    </div>
  </div>
</template>

<script>
import { getTreeMenuInfo } from '@/api/web'
import { debugService } from '@/api/admin/debug'
import { getServiceInfo } from '@/api/admin/service'
import { getLoginType, getUserInfo } from '@/utils/auth'
export default {
  data() {
    return {
      search: '',
      menu_info: {
        apps: []
      },
      apps: [],
      apps_info: {
        base: {
          serviceUrl: '',
          baseUrl: '',
          returnDemo:''
        },
        params:[],
      },
      app_id: '',
      params: [],
      debug: {
        request: false,
        data: ''
      },
      url: '',
      loading: false,
      options: [],
      prd_from: {
        prd_from:[]
      },
      selectItem:{},
      is_request_debug: false
    }
  },
  computed: {
    isVisitor() {
      return getLoginType() === 'visitor' ? true : false
    }
  },
  mounted() {
    if (this.$route.query.id){
      this.getServiceInfo(this.$route.query.id)
    }
  },
  methods: {
    querySearch(queryString, cb) {
      let temp = []
      for (const iterator of this.selectItem.forSelect.split(',')) {
        let value = {"value":iterator}
        temp.push(value)
      }
      cb(temp)
    },
    selectOptionApps(val){
      this.selectApps(val)
    },
    remoteMethod(query) {
      if (query !== '') {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          this.options = this.menu_info.apps.filter(item => {
            return item.appName.toLowerCase().indexOf(query.toLowerCase()) > -1
          })
          console.log(this.options)
        })
      }else {
        this.options = [];
      }
    },
    copy(text) {
      const vm = this;
      this.$copyText(text).then((res)=>{
        console.log(res)
        vm.$message.success('复制成功')
      },(err)=>{
        console.log(err)
        vm.$message.error('复制失败')
      })
    },
    // 调用测试接口
    sendApi(rules) {
      const vm = this;
      vm.$refs[rules].validate((valid)=>{
        if (valid) {
          let params = {
            appId:this.app_id,
          }
          let isvalid = true
          for (const item of vm.prd_from.params) {
            if (item.value !== '') {
              params[item.paramName] = item.value
            }
          }
          if (!isvalid) {
            return
          } 
          const loading = this.$loading({
            lock: true,
            text: '正在调试，请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          debugService(params).then((res)=>{
            vm.debug.request = true
            loading.close()
            if (res.code === '20000') {
              vm.debug.ok = true
              vm.debug.data = res.data
              vm.is_request_debug = true
            }
            if (res.code === '30006') {
              vm.debug.ok = false
              vm.debug.data = `服务未开启`
            }
            if (res.code === '30007') {
              vm.debug.ok = false
              vm.debug.data = `游客无权限调用`
            }
            if (res.code === '30008') {
              vm.debug.ok = false
              vm.debug.data = `用户无此服务调用权限`
            }
          })
        }
      })
      
      
      
    },
    async selectApps(id) {
      const vm = this;
      vm.app_id = id
      vm.apps_info.id = false
      vm.debug.request = false
      let response = await getServiceInfo({id:id})
      if (response.code === '20000') {
        vm.apps_info = response.data
        // let userid_str = '${userid}';
        let token = getLoginType() === 'visitor'? '${token}':  JSON.parse(getUserInfo()).token
        vm.url = `url: ${vm.apps_info.base.baseUrl}${vm.apps_info.base.serviceUrl}
Request Method: POST        
Request Header：
token : ${token}
Content-Type : application/x-www-form-urlencoded
        `
        let temp = []
        for (const item of response.data.params) {
          let value = {
            appId: item.appId,
            forSelect: item.forSelect,
            paramShowname: item.paramShowname,
            paramName: item.paramName,
            paramDescription: item.paramDescription,
            id: item.paramDescription,
            required: item.required,
            value: ''
          }
          temp.push(value)
        }
        vm.params = temp;
        vm.prd_from.params = temp
      }
    },
    async getServiceInfo(id) {
      const vm = this;
      let id_str = String(id.replace('/',''))
      let response = await getTreeMenuInfo({id:id_str})
      if (response.code === '20000') {
        vm.menu_info = response.data
        vm.apps = response.data.apps
      }
    },
    async searchApps() {
      const vm = this;
      let temp = []
      for (const item of this.apps) {
       
        if(item.appName.indexOf(vm.search) !== -1) {
          temp.push(item)
        }
      }
      vm.menu_info.apps = temp
    }
  },
  watch:{
    $route: {
      handler: function(val){
        Object.assign(this.$data, this.$options.data())
        this.getServiceInfo(val.query.id)
      },
      // 深度观察监听
      deep: true
    }
    // console.log(this.$route)
  },
}
</script>
<style lang="scss" scoped>
@import "../../styles/web";
.beizhu {
  color:red;
  font-size: 12px;
  padding-left: 30px;
  padding-top: 10px;
}
</style>